const bleNative = {
  name: 'UniAppBleNative',
  bleState: { available: false, discovering: false },
  listener: null,
  
  // 初始化蓝牙适配器
  async init() {
    try {
      // 检查蓝牙适配器状态
      const adapterState = await this.getBluetoothAdapterState();
      
      if (!adapterState.available) {
        throw new Error('蓝牙适配器不可用');
      }
      
      this.bleState.available = true;
      return { available: true, discovering: false };
      
    } catch (error) {
      console.error('蓝牙初始化失败:', error);
      throw error;
    }
  },
  
  // 获取蓝牙适配器状态
  getBluetoothAdapterState() {
    return new Promise((resolve, reject) => {
      uni.getBluetoothAdapterState({
        success: (res) => {
          this.bleState.available = res.available;
          this.bleState.discovering = res.discovering;
          resolve(res);
        },
        fail: (err) => {
          console.error('获取蓝牙状态失败:', err);
          reject(err);
        }
      });
    });
  },
  
  // 打开蓝牙适配器
  openBluetoothAdapter() {
    return new Promise((resolve, reject) => {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log('打开蓝牙适配器成功');
          this.bleState.available = true;
          resolve(res);
        },
        fail: (err) => {
          console.error('打开蓝牙适配器失败:', err);
          
          // 错误处理
          let errorMsg = '蓝牙初始化失败';
          if (err.errCode === 10001) {
            errorMsg = '蓝牙适配器不可用，请检查手机蓝牙是否开启';
          } else if (err.errCode === 10002) {
            errorMsg = '没有找到指定蓝牙设备';
          } else if (err.errCode === 10003) {
            errorMsg = '连接失败，请重试';
          } else if (err.errCode === 10004) {
            errorMsg = '没有找到指定服务';
          } else if (err.errCode === 10005) {
            errorMsg = '没有找到指定特征值';
          } else if (err.errCode === 10006) {
            errorMsg = '当前连接已断开';
          } else if (err.errCode === 10007) {
            errorMsg = '当前特征值不支持此操作';
          } else if (err.errCode === 10008) {
            errorMsg = '其余所有系统上报的异常';
          } else if (err.errCode === 10009) {
            errorMsg = 'Android 系统特有，系统版本低于 4.3 不支持 BLE';
          } else if (err.errCode === 10012) {
            errorMsg = '连接超时';
          } else if (err.errCode === 10013) {
            errorMsg = '缺少位置权限，请授权位置权限';
          }
          
          reject(new Error(errorMsg));
        }
      });
    });
  },
  
  // 开始扫描设备
  async startScan(options = {}) {
    try {
      // 确保蓝牙适配器已打开
      if (!this.bleState.available) {
        await this.openBluetoothAdapter();
      }
      
      const result = await new Promise((resolve, reject) => {
        uni.startBluetoothDevicesDiscovery({
          services: options.services || [],
          allowDuplicatesKey: true,
          interval: 0,
          success: resolve,
          fail: reject
        });
      });
      
      this.bleState.discovering = true;
      return result;
      
    } catch (error) {
      console.error('开始扫描失败:', error);
      throw error;
    }
  },
  
  // 其他方法保持不变...
  // ... [之前的其他方法实现]
  
  // 设置监听器
  setListener(listener) {
    this.listener = listener;
    
    // 监听蓝牙适配器状态变化
    uni.onBluetoothAdapterStateChange((res) => {
      this.bleState.available = res.available;
      this.bleState.discovering = res.discovering;
      
      if (this.listener && this.listener.onNativeBluetoothEnableChange) {
        this.listener.onNativeBluetoothEnableChange(res.available);
      }
    });
    
    // 监听设备发现
    uni.onBluetoothDeviceFound((res) => {
      const devices = res.devices;
      if (devices.length && this.listener && this.listener.onNativeBleDeviceFound) {
        const device = devices[0];
        const formattedDevice = {
          deviceId: device.deviceId,
          name: device.name,
          bluetoothName: device.name,
          localName: device.localName,
          rssi: device.RSSI,
          advertisData: device.advertisData,
          manufacturerData: device.manufacturerData,
          services: [] // 需要连接后才能获取服务
        };
        this.listener.onNativeBleDeviceFound(formattedDevice);
      }
    });
    
    // 监听特征值变化
    uni.onBLECharacteristicValueChange((res) => {
      if (this.listener && this.listener.onNativeCharacteristicValueChange) {
        this.listener.onNativeCharacteristicValueChange({
          deviceId: res.deviceId,
          serviceId: res.serviceId,
          characteristicId: res.characteristicId,
          data: Array.from(new Uint8Array(res.value))
        });
      }
    });
  }
};

export default bleNative;